// pages/city/index.ts
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from "~/stores/app"
import type { itemState, cityInfoState } from '~/../typings/types/city'
import { back, deepClone } from '~/utils/util'
import * as watch from '~/utils/watch'
let cityList: itemState[] = []
interface showState {
  label: string
  children: itemState[]
}
interface historyItem {
  label: string
  value: string
}

interface searchItem {
  label: string
  value: string
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '' as string,
    historyList: [] as historyItem[],
    pageType: 'homeTop' as 'homeTop' | 'star' | 'end' | 'order' | 'destination' | 'endChoose',
    checked: [] as itemState[],
    showList: [] as showState[],
    star: '',
    end: '',
    isAllCheck: false,
    searchArr: [] as searchItem[],
    searchValue: false,
    cityInfo: {
      doArea: [],
      doSiteList: []
    } as cityInfoState
  },
  handCurrenClick(e: any) {
    const idx = e.target.dataset.idx
    const { checked } = this.data
    checked.splice(idx + 1, checked.length - idx + 1)
    this.setData({
      checked
    })
    this.getShowList()
    this.allCheckChange()
  },
  searchFun(e: any) {
    const keyword = e.detail.value
    const arr = [] as searchItem[]
    if (!keyword) {
      this.setData({
        searchArr: [],
        searchValue: false
      })
      return
    }
    cityList.forEach((el: any) => {
      el.children.forEach((element: any) => {
        if (element.label.includes(keyword)) {
          arr.push({
            label: `${element.label}(${el.label})`,
            value: `${el.label}-${element.label}`
          })
        }
        if (element.children) {
          element.children.forEach((item: any) => {
            if (item.label.includes(keyword)) {
              arr.push({
                label: `${item.label}(${el.label}-${element.label})`,
                value: `${el.label}-${element.label}-${item.label}`
              })
            }
          });
        }
      });
    })
    this.setData({
      searchArr: arr,
      searchValue: true
    })
  },
  bindsearch(e: any) {
    const params = e.currentTarget.dataset.item
    const item = {
      star: this.data.star,
      end: params.value
    }
    this.handSearchJump(item)
  },
  allCheckChange() {
    if (this.data.checked.length > 1) {
      this.setData({
        isAllCheck: true
      })
    } else {
      this.setData({
        isAllCheck: false
      })
    }
  },
  getArr(arr: itemState[], children: itemState[], index = 0, newArr = [] as itemState[]): itemState[] {
    const checkInfo = arr[index]
    const info = children.find(el => el.label === checkInfo.label)
    if (info) {
      const newInfo = JSON.parse(JSON.stringify(info))
      delete newInfo.children
      newArr.push(newInfo)
      if (info.children && info.children.length > 0 && index < arr.length - 1) {
        return this.getArr(arr, info.children, index + 1, newArr)
      }
    }
    return newArr
  },
  handSubmit() {
    const eventChannel = this.getOpenerEventChannel()
    const arr = this.getArr([...this.data.checked], cityList)
    eventChannel.emit('chooseEvent', arr);
    if (this.data.pageType === 'end') {
      if (this.data.star) {
        const end = deepClone(arr).map((el: itemState) => {
          return el.label
        }).join('-')
        const item = {
          star: this.data.star,
          end
        }
        this.handSearchJump(item)
        return
      }
    }
    back()
  },
  handRemove() {
    wx.showModal({
      title: '温馨提示',
      content: '确认要清空搜索记录吗?',
      cancelText: '我再想想',
      confirmText: '确认清空',
      showCancel: true,
      success: (res) => {
        if (res.confirm) {
          this.setData({
            historyList: []
          })
          wx.removeStorageSync('historyEnd')
        }
        console.log(res)
      }
    })
  },
  handHistoryClick(e: any) {
    const info = this.data.historyList[e.target.dataset.index]
    const item = {
      star: this.data.star,
      end: info.value
    }
    this.handSearchJump(item)
  },
  handSearchJump(e: any) {
    const { historyList } = this.data
    const { end } = e
    const historyIndex = historyList.findIndex((el) => el.value == end)
    if (historyIndex >= 0) {
      historyList.splice(historyIndex, 1)
    }
    const names = end.split('-')
    historyList.unshift({
      label: names[names.length - 1],
      value: end
    })
    if (historyList.length > 4) {
      historyList.splice(4, 1)
    }
    this.setData({
      historyList
    })
    this.setHistory()
    const pages = getCurrentPages();
    const page = pages[pages.length - 2];
    if (page.route == 'pages/search/result') {
      console.log(e)
      const arr = e.end.split('-').map((el: string) => {
        return {
          label: el
        }
      })
      const abb = this.getArr(arr, cityList)
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.emit('chooseEvent', abb);
      back()
    } else {
      wx.redirectTo({
        url: `/pages/search/result?city=${encodeURIComponent(JSON.stringify(e))}`
      })
    }
  },
  getHistory() {
    const info = wx.getStorageSync('historyEnd')
    if (info) {
      this.setData({
        historyList: JSON.parse(info)
      })
    } else {
      this.setData({
        historyList: []
      })
    }
  },
  setHistory() {
    if (this.data.historyList.length > 0) {
      wx.setStorageSync('historyEnd', JSON.stringify(this.data.historyList))
    }
  },
  handActive(e: any) {
    const labelInfo = this.data.showList.find(el => el.label === e.target.dataset.idx)
    if (!labelInfo) return
    const info = labelInfo.children[e.target.dataset.n]
    if (info.children && info.children.length > 0) {
      const arr = this.data.checked
      arr.push(info)
      this.setData({
        checked: arr
      })
      this.getShowList()
    } else {
      const eventChannel = this.getOpenerEventChannel()
      console.log(info)
      const arr = this.getArr([...this.data.checked, info], cityList)
      eventChannel.emit('chooseEvent', arr);
      if (this.data.pageType === 'end') {
        if (this.data.star) {
          const end = deepClone(arr).map((el: itemState) => {
            return el.label
          }).join('-')
          const item = {
            star: this.data.star,
            end
          }
          this.handSearchJump(item)
          return
        }
      }
      back()
    }
    this.allCheckChange()
  },
  getShowList() {
    let arr: itemState[] = cityList
    if (this.data.checked.length > 0) {
      this.data.checked.forEach(el => {
        const info: itemState | undefined = arr.find((item: itemState) => item.label === el.label)
        if (info && info?.children) {
          arr = info.children
        }
      })
    }
    let newArr: showState[] = []
    arr.forEach(el => {
      const index = newArr.findIndex(item => item.label === el.pinYin)
      if (index >= 0) {
        const info = newArr[index]
        if (info && info?.children) {
          info.children.push(el)
        }
      } else {
        newArr.push({
          label: el.pinYin,
          children: [el]
        })
      }
    })
    this.setData({
      showList: newArr.sort((a, b) => (a.label > b.label) ? 1 : -1)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(this: any, e: any) {
    this.storeBinding = createStoreBindings(this, {
      store,
      fields: {
        cityName: 'getCityName',
        cityInfo: 'cityInfo',
      },
      actions: ['initCitys']
    });
    watch.setWatcher(this);
    this.getHistory()
    this.setData({
      pageType: e.type
    })
    if (e.city) {
      const item: {
        star?: string
        end?: string
      } = JSON.parse(decodeURIComponent(e.city));
      if (item.star) {
        this.setData({
          star: item.star
        })
      } else if (item.end) {
        this.setData({
          end: e.end
        })
      }
    }

    if (e.type === 'star') {
      this.setData({
        title: '选择出发城市'
      })
    } else if (e.type === 'end') {
      this.setData({
        title: '选择到达城市'
      })
    } else if (e.type === 'endChoose') {
      this.setData({
        title: '选择到达城市'
      })
    } else if (e.type === 'order') {
      this.setData({
        title: '选择城市'
      })
    } else if (e.type === 'destination') {
      this.setData({
        title: '选择目的地城市'
      })
    } else {
      this.setData({
        title: '选择到达城市'
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    if(this.data.cityInfo.doArea.length === 0 || this.data.cityInfo.doSiteList.length === 0) {
      this.initCitys()
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload(this: any) {
    this.storeBinding.destroyStoreBindings();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  watch: {
    cityInfo: function (e: cityInfoState) {
      if (e.doArea.length > 0) {
        let name: 'doSiteList' | 'doArea' = 'doSiteList'
        if (['end', 'destination', 'endChoose'].includes(this.data.pageType)) {
          name = 'doArea'
        }
        const data = e[name]
        cityList = data
        this.getShowList()
      }
    }
  }
})